[val, text, raw] = xlsread('VNIBOR.xlsx',5);

Y = val(:,1);
X = val(:,2:end);
%get the mname of predictors
namePredictors = text(1,3:end);

ctree = fitctree(X,Y,'PredictorNames',namePredictors); 

view(ctree,'mode','graph') % text description

resuberror = resubLoss(ctree,'subtrees','all');
[E,SE,Nleaf,BestLevel] = cvLoss(ctree,'subtrees','all');
[resuberror E]

%% predict



windowSize = 50; % 5yr
N = size(Y,1);
result_predict = zeros(N - windowSize,2)


for i = 1 : N - windowSize
%     X_training = X(i:windowSize+i-1,:);
%     Y_training = Y(i:windowSize+i-1);
    X_training = X(1:windowSize+i-1,:);
    Y_training = Y(1:windowSize+i-1);
    ctree1 = fitctree(X_training,Y_training,'PredictorNames',namePredictors); 
%     view(ctree1,'mode','graph') % text description
    resuberror1 = resubLoss(ctree1,'subtrees','all');
    [E1,SE1,Nleaf1,BestLevel1] = cvLoss(ctree1,'subtrees','all');
    [resuberror1 E1]
%     if(E1(1) > E1(2))
%         newTree1 = prune(ctree1,'Level',1);
%     else
        newTree1 = ctree1;
%     end
    X_predictor = X(i+windowSize,:);
    [Y_predict, Y_score] = predict(newTree1,X_predictor);
    result_predict(i,1) = Y_predict;
    result_predict(i,2) = Y_score(1);
%     [resuberror1 E1]
end
[Y(windowSize+1:end) result_predict]
sum(Y(windowSize+1:end)==result_predict(:,1))./(N-windowSize)

%%

dates = datenum(text(2:end,1))
dates2 = dates(windowSize+1:end)
r = val(:,1)
r2 = r(windowSize+1:end)
figure(1)
subplot(2,1,1);plot(dates2,r2)
title('VNIBOR 1M')
datetick('x',12)
subplot(2,1,2); 
scatter(dates2,Y(windowSize+1:end),'ro')
hold on
scatter(dates2,result_predict(:,1),'bx')
datetick('x',12)
title('Movement direction')
legend('actual','forecast')
hold off